package com.studio77.guessLyric.sprite;

import java.util.ArrayList;
import java.util.List;

import com.studio77.guessLyric.core.GameSystem;
import com.studio77.guessLyric.scene.GameScene;
import com.wiyun.engine.nodes.Node;

public class DaanListControl extends Node {

	private List<DaanItem> daanItems;
	private String daan;
	private List<String> currentDaan;
	List<KeyItem> keyItems;

	public DaanListControl() {
		keyItems = new ArrayList<KeyItem>();
		daanItems = new ArrayList<DaanItem>();
		currentDaan = new ArrayList<String>();
		for (int i = 0; i < 9; i++) {
			daanItems.add(new DaanItem());
		}
	}

	public float start(String d) {
		currentDaan.clear();
		keyItems.clear();
		float totalWidth = 0f;
		daan = d;
		this.removeAllChildren(false);
		for (int i = 0; i < d.length(); i++) {
			float x = (GameSystem.KeyWidth + 5) * i;
			daanItems.get(i).setPosition(x, 0);
			daanItems.get(i).setAnchorX(0f);
			this.addChild(daanItems.get(i));
			daanItems.get(i).clearDaan();

			currentDaan.add("");
			keyItems.add(null);
		}
		totalWidth = d.length() * (GameSystem.KeyWidth + 5) - 5;
		return totalWidth;
	}

	/**
	 * 是否能够键入
	 * 
	 * @return
	 */
	public boolean isCanTypeNewChar() {
		boolean result = false;
		for (int i = 0; i < currentDaan.size(); i++) {
			if (currentDaan.get(i).equals("")) {
				result = true;
				break;
			}
		}
		return result;
	}

	/**
	 * 清除内容
	 * 
	 * @param daanItem
	 */
	public void onItemCleaned(DaanItem daanItem) {

		int index = daanItems.indexOf(daanItem);

		if (index >= 0 && index < currentDaan.size()) {
			currentDaan.set(index, "");

			// 恢复键盘
			KeyItem keyitem = keyItems.get(index);
			if (keyitem != null) {
				keyitem.setVisible(true);
				keyItems.set(index, null);
			}
		}
	}

	public void onKeyItemClick(KeyItem keyItem, String myKeyString) {
		for (int i = 0; i < currentDaan.size(); i++) {
			if (currentDaan.get(i).equals("")) {
				keyItem.setVisible(false);
				currentDaan.set(i, myKeyString);
				keyItems.set(i, keyItem);
				daanItems.get(i).setDaan(myKeyString);
				break;
			}
		}

		// 判断答案是否正确
		if (daan.equalsIgnoreCase(getDaanStr())) {
			// 通知GameLayer，完成关卡
			GameScene.make().getLayer().completeQuestion(false);
		}
	}

	private String getDaanStr() {
		String result = "";
		for (int i = 0; i < currentDaan.size(); i++) {
			result += currentDaan.get(i);
		}
		return result;
	}

}
